package com.company.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.project.core.Result;
import com.company.project.core.ResultCode;
import com.company.project.core.ResultGenerator;
import com.company.project.dao.LoginMapper;
import com.company.project.model.Login;
import com.company.project.model.LoginInfo;
import com.company.project.model.ShopLogin;
import com.company.project.model.User;
import com.company.project.model.request.EditPass;
import com.company.project.model.request.EditPassForm;
import com.company.project.model.request.QueryParams;
import com.company.project.service.AdminUserService;
import com.company.project.service.ShopLoginService;
import com.company.project.utils.MD5Util;
import com.company.project.utils.UploadUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by CodeGenerator on 2020/04/21.
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private AdminUserService adminUserService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ShopLoginService shopLoginService;
    @Autowired
    private LoginMapper loginMapper;

    /**
     * 登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        //uariqbgqarifbdfe
        if (user == null) {
            return ResultGenerator.genFailResult("用户名或密码错误");
        }
        return adminUserService.login(user);
    }

    /**
     * 注销
     */
    @PostMapping("/logout")
    public Result logout(@RequestBody Integer id) {
        if (id == 0) {
            return ResultGenerator.genFailResult("注销出错");
        }
        return adminUserService.logout(id);
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        if (user == null) {
            return ResultGenerator.genFailResult("");
        }
        return adminUserService.register(user);
    }

    /**
     * 发送验证码
     */
    @PostMapping("/emailCode")
    public Result sendCode(@RequestBody String email) {
        if (StringUtils.isEmpty(email)) {
            return ResultGenerator.genFailResult("发送失败!");
        }
        return adminUserService.sendCode(email);
    }

    /**
     * 检查用户名是否存在
     */
    @GetMapping("/checkEmail")
    public Result checkEmail(String email) {
        if (StringUtils.isEmpty(email)) {
            return ResultGenerator.genFailResult("");
        }
        User user = adminUserService.findBy("username", email);
        if (user != null) {
            return ResultGenerator.genFailResult("该邮箱已被注册！");
        }
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/get/{id}")
    public Result getUser(@PathVariable("id") Integer id) {
        if (id != 0) {
            Object o = redisTemplate.opsForValue().get(id);
            if (o == null) {
                Result result = new Result();
                result.setCode(ResultCode.LOGIN_EXPIRED);
                result.setMessage("登录已过期，请重新登录");
                return result;
            }
            User user = adminUserService.findBy("userId", id);
            return ResultGenerator.genSuccessResult(user);
        }
        return ResultGenerator.genFailResult("没有登录");
    }

    /**
     * 显示图片
     *
     * @param fileName
     * @param response
     */
    @RequestMapping(value = "/image/get/{fileName:.+}")
    public void getImage(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        response.addHeader("Access-Control-Allow-Origin", "*");
        String projectPath = System.getProperty("user.dir");
        String filePath = projectPath + "/src/main/resources/static";
        FileInputStream fis = null;
        response.setContentType("image/gif");
        try {
            OutputStream out = response.getOutputStream();
            File file = new File(filePath + File.separator + fileName);
            fis = new FileInputStream(file);
            byte[] b = new byte[fis.available()];
            fis.read(b);
            out.write(b);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 上传图片
     *
     * @param file
     * @param response
     * @return
     */
    //TODO 需要修改返回值类型，不然AopLog报错
    @RequestMapping(value = "/upload/img")
    public String uploadImg(MultipartFile file, HttpServletResponse response) {
        if (file.isEmpty()) {
            return "null";
        }
        // 拿到文件名
        String filename = file.getOriginalFilename();
        // 存放上传图片的文件夹
        File fileDir = UploadUtils.getImgDirFile();
        // 输出文件夹绝对路径  -- 这里的绝对路径是相当于当前项目的路径而不是“容器”路径
        System.out.println(fileDir.getAbsolutePath());
        try {
            // 构建真实的文件路径
            File newFile = new File(fileDir.getAbsolutePath() + File.separator + filename);
            System.out.println(newFile.getAbsolutePath());
            // 上传图片到 -》 “绝对路径”
            file.transferTo(newFile);
            return filename;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "null";
    }

    /**
     * 修改密码
     */
    @PostMapping("/updatePwd")
    public Result updatePwd(@RequestBody EditPassForm editPassForm) {
        if (editPassForm == null) {
            return ResultGenerator.genFailResult("参数错误");
        }
        return adminUserService.updatePwd(editPassForm);
    }


    /**
     * 查询用户列表
     */
    @GetMapping("/list")
    public Result getUserList(QueryParams queryParams) {
        return adminUserService.getUserList(queryParams);
    }

    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        User query = adminUserService.findBy("username", user.getUsername());
        if (query != null) {
            return ResultGenerator.genFailResult("用户名已存在");
        }
        user.setStatus("1");
        user.setCreatTime(new Date());
        user.setPassword(MD5Util.md5("123456", user.getUsername()));
        adminUserService.save(user);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody Integer id) {
        if (id == null) {
            return ResultGenerator.genFailResult("参数错误");
        }
        return adminUserService.delete(id);
    }

    @PostMapping("/deleteAll")
    public Result deleteAll(@RequestBody List<User> userList) {
        if (userList == null || userList.size() <= 0) {
            return ResultGenerator.genFailResult("参数错误");
        }
        for (User user : userList) {
            adminUserService.delete(user.getUserId());
        }
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/update")
    public Result update(@RequestBody User user) {
        if (user == null) {
            return ResultGenerator.genFailResult("参数错误");
        }
        return adminUserService.updateInfo(user);
    }

    @PostMapping("/edit")
    public Result detail(@RequestBody User user) {
        User entity = adminUserService.findBy("username", user.getUsername());
        entity.setName(user.getName());
        entity.setRole(user.getRole());
        adminUserService.update(entity);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/all")
    public Result all() {
        return ResultGenerator.genSuccessResult(adminUserService.findAll());
    }

    @PostMapping("/handle")
    public Result adminLogin(@RequestBody User user, HttpServletRequest request) {

        if (user == null) {
            return ResultGenerator.genFailResult("用户名或者密码错误！");
        }
        String pass = MD5Util.md5(user.getPassword(), user.getUsername());
        if ("管理员".equals(user.getRole())) {
            User entity = adminUserService.findBy("username", user.getUsername());
            if(entity.getRole().equals("管理员")) {
                if (entity.getPassword().equals(pass)) {
                    List<String> access = new ArrayList<>();
                    access.add("admin");
                    entity.setAccess(access);
                    redisTemplate.opsForValue().set("user", entity.getName());
                    redisTemplate.opsForValue().set("role", entity.getRole());
                    Login login = new Login();
                    login.setId(entity.getUserId());
                    login.setName(entity.getName());
                    login.setTime(new Date());
                    login.setIp(request.getRemoteAddr());
                    login.setAccess("admin");
                    loginMapper.insert(login);
                    return ResultGenerator.genSuccessResult(entity);
                }
            }
        } else if("商家".equals(user.getRole())) {
            ShopLogin shop = shopLoginService.findBy("email", user.getUsername());
            if(shop == null) {
                return ResultGenerator.genFailResult("用户名或者密码错误！");
            }
            if(shop.getPassword().equals(pass)) {
                List<String> access = new ArrayList<>();
                access.add("shop");
                shop.setAccess(access);
                redisTemplate.opsForValue().set("user", shop.getName());
                redisTemplate.opsForValue().set("role", "商家");
                Login login = new Login();
                login.setId(shop.getShopId());
                login.setName(shop.getName());
                login.setTime(new Date());
                login.setIp(request.getRemoteAddr());
                login.setAccess("shop");
                loginMapper.insert(login);
                return ResultGenerator.genSuccessResult(shop);
            }
            return ResultGenerator.genFailResult("用户名或者密码错误！");
        }
        return ResultGenerator.genFailResult("用户名或者密码错误！");
    }

    @PostMapping("/info")
    public Result getInfo(@RequestBody String id) {
        String tag = id.substring(0, 4);
        String idd = id.substring(4, 5);
        LoginInfo info = new LoginInfo();
        if (tag.equals("shop")) {
            ShopLogin shop = shopLoginService.findBy("shopId", Integer.parseInt(idd));
            info.setName(shop.getName());
            List<String> list = new ArrayList<>();
            list.add("shop");
            info.setAccess(list);
            info.setId(shop.getShopId());
            info.setAvatar("");
        } else if (tag.equals("user")) {
            User user = adminUserService.findBy("userId", Integer.parseInt(idd));
            info.setName(user.getName());
            List<String> list = new ArrayList<>();
            list.add("admin");
            info.setAccess(list);
            info.setId(user.getUserId());
            info.setAvatar("");
        }
        return ResultGenerator.genSuccessResult(info);
    }


}
